package associations;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class AssociationTest {
    public static void main(String[] args) {
        Configuration configuration = new Configuration().configure();
        SessionFactory sessionFactory = configuration.buildSessionFactory();
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();

//        一对多
//        oneToMany(session);

//        多对多
        Task task1 = new Task();
        task1.setTaskName("写文档");
        Task task2 = new Task();
        task2.setTaskName("写代码");
        Employee employee1 = new Employee();
        employee1.setName("liushuo");
        Employee employee2 = new Employee();
        employee2.setName("zhangsan");
        task1.getEmployees().add(employee1);
        task2.getEmployees().add(employee1);
        task2.getEmployees().add(employee2);

        session.save(task1);
        session.save(task2);
        session.save(employee1);
        session.save(employee2);


        transaction.commit();
        session.close();
        sessionFactory.close();
    }

    private static void oneToMany(Session session) {
        Department department = new Department();
        department.setDepartmentName("技术部");
        Employee employee1 = new Employee();
        employee1.setName("liushuo");
        employee1.setDepartment(department);

        Employee employee2 = new Employee();
        employee2.setName("zhangsan");
        employee2.setDepartment(department);

        department.getEmployees().add(employee1);
        department.getEmployees().add(employee2);

//        session.save(employee1);
//        session.save(employee2);
        session.save(department);
    }
}
